<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ResultsController extends Controller
{
    /**
     * Serve a read-only file from the project's `results` directory.
     * Only files that start with `visualization_omr_` and have an image extension
     * will be returned. Path traversal is rejected.
     *
     * Example URL: /results/visualization_omr_2022年12月02日小测_001.png
     */
    public function show(Request $request, $filename)
    {
        // Basic safety checks
        if (strpos($filename, '..') !== false) {
            abort(400, 'Invalid filename');
        }

        // Only allow files that begin with the expected prefix
        if (!str_starts_with($filename, 'visualization_omr_')) {
            abort(404);
        }

        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $allowed = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
        if (!in_array($ext, $allowed, true)) {
            abort(404);
        }

        // Resolve real paths to avoid traversal
        $base = realpath(base_path('results'));
        if ($base === false) {
            abort(500, 'Results directory not found');
        }

        $fullPath = realpath($base . DIRECTORY_SEPARATOR . $filename);
        if ($fullPath === false) {
            abort(404);
        }

        // Ensure the resolved path is inside the results directory
        if (strpos($fullPath, $base) !== 0) {
            abort(403, 'Forbidden');
        }

        if (!is_file($fullPath) || !is_readable($fullPath)) {
            abort(404);
        }

        // Serve the file (let Laravel/Symfony set appropriate headers)
        return response()->file($fullPath, [
            'Cache-Control' => 'public, max-age=3600, immutable'
        ]);
    }
}
